package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);

        //清除缓存
        redisTemplate.delete("dish_" + dishDto.getCategoryId());

        return R.success("新增成功");
    }

    /**
     * 分页条件查询
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {

        //构造分页对象
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);
        //构造条件对象
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        //添加排序条件
        queryWrapper.orderByAsc("status").orderByDesc("update_time");
        //执行分页查询
        dishService.page(pageInfo1, queryWrapper);

        //对 Page<Dish> pageInfo1 做数据处理
        Page<DishDto> pageInfo2 = new Page<>(page, pageSize);

        //将 pageInfo1 的数据拷贝到 pageInfo2 中,除了 records 中的 list集合不要拷贝
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");

        //将 pageInfo1 的 list<Dish> 转为 list<DishDto>
        List<DishDto> dishDtoList = new ArrayList<>();

        //遍历 pageInfo1 的 list<Dish> 集合
        for (Dish dish : pageInfo1.getRecords()) {
            //将 Dish 转换成 DishDto
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            //添加分类名称
            Category category = categoryService.getById(dish.getCategoryId());//获取菜品分类id然后得到菜品分类
            dishDto.setCategoryName(category.getName());//获取菜品分类名称

            //添加到集合中
            dishDtoList.add(dishDto);
        }
        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);
    }

    /**
     * 根据ID查询菜品及菜品口味信息**
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        //清除缓存
        Set keys = redisTemplate.keys("dish_*");//获取所有以dish_xxx开头的key
        redisTemplate.delete(keys);//删除这些key
        return R.success("修改菜品信息成功");
    }

    /**
     * 根据分类ID查询菜品列表**
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //从Redis中获取缓存数据
        List<DishDto> dishDtoRedisList = (List<DishDto>) redisTemplate.opsForValue().get("dish_" + dish.getCategoryId());
        if (dishDtoRedisList!=null){
            //如果存在,就不需要查询数据库,直接返回
            return R.success(dishDtoRedisList);
        }
        //如果不存在,要从数据库查询,执行下面的操作

        //构造查询条件
        QueryWrapper<Dish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,"category_id",dish.getCategoryId());
        //添加条件
        queryWrapper.eq("status",1);
        //添加排序条件
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        //查询
        List<Dish> dishList = dishService.list(queryWrapper);

        //转换数据,将 Dish转换成 DishDto
        List<DishDto> dishDtoList=new ArrayList<>();
        for (Dish dish1 : dishList) {
            DishDto dishDto=new DishDto();
            //基本数据拷贝
            BeanUtils.copyProperties(dish1,dishDto);
            //添加口味
            QueryWrapper<DishFlavor> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("dish_id",dish1.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }

        //将查询到的数据存到 Redis中,设置存活时间
        redisTemplate.opsForValue().set("dish_" + dish.getCategoryId(),dishDtoList,30, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
